#include "NameSvrClient.h"

LoggerPtr NameSvrClientManager::_logger = Logger::getLogger("NameSvrClientManager");

int NameSvrClientManager::init(CnfSvrClient * csc) {
	_csc = csc;
	_nsc = NULL;
	pthread_mutex_init(&_mutex, NULL);
	LOG4CXX_INFO(_logger, __FUNCTION__ << ", ok!");
	return 1;
}

NameSvrClient * NameSvrClientManager::get_name_svr_client() {
	NameSvrClient * nsc;
	pthread_mutex_lock(&_mutex);
	if (NULL != _nsc) {
		pthread_mutex_unlock(&_mutex);
		return _nsc;
	}
	NS_CNF ns;
	int ret = _csc->get_ns_cnf(ns);
	if (ret < 0) {
		pthread_mutex_unlock(&_mutex);
		LOG4CXX_ERROR(_logger, __FUNCTION__ << ", could not get ns cnf ret:" << ret);
		return NULL;
	}
	nsc = new NameSvrClient;
	ret = nsc->init(ns.ip.c_str(), ns.port, ns.client_conn_pool_size, ns.socket_conn_timeout, ns.socket_send_timeout, \
				ns.socket_recv_timeout, ns.socket_max_response_size);
	if (ret < 0) {
		pthread_mutex_unlock(&_mutex);
		delete nsc;
		LOG4CXX_ERROR(_logger, __FUNCTION__ << ", ns svr client init err, ret:" << ret);
		return NULL;
	}
	_nsc = nsc;
	pthread_mutex_unlock(&_mutex);
	LOG4CXX_INFO(_logger, __FUNCTION__ << ", insert ns client to ns client manager, svr ip:" << ns.ip << \
					", port:" << ns.port);
	return _nsc;
}
